package vip.xiaonuo.hontu.issued.task;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.aliyun.oss.common.utils.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xxl.job.core.handler.annotation.XxlJob;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CopyOnWriteArraySet;


import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import vip.xiaonuo.core.timer.TimerTaskRunner;
import vip.xiaonuo.facedoor.modular.devicebase.entity.DeviceBase;
import vip.xiaonuo.facedoor.modular.devicebase.service.DeviceBaseService;
import vip.xiaonuo.hontu.issued.response.PersonUUIDSwitchResponse;
import vip.xiaonuo.hontu.issued.util.HT_DEVICE_POST;
import vip.xiaonuo.hontu.issued.util.HongTuRequestUrl;

@Component
@Slf4j
public class HtDeviceHeartBeatTask implements TimerTaskRunner {

  private static final CopyOnWriteArraySet<String> currentExecuteTask = new CopyOnWriteArraySet();


  @Autowired
  private DeviceBaseService deviceBaseService;



  @Override
  public void action(String jobParams,String taskId) {
    synchronized (HtDeviceHeartBeatTask.class) {
      if (currentExecuteTask.contains(taskId)) {
        log.error("当前任务正在执行请稍后！");
        return;
      }
      log.info("心跳任务开始执行" + taskId + DateUtil.formatAlternativeIso8601Date(new Date()));
      currentExecuteTask.add(taskId);
    }
    // 心跳
    heartBeat();
    log.info("心跳任务执行结束" + taskId);
    currentExecuteTask.remove(taskId);
  }

  @Override
  @XxlJob("HTDeviceHeartBeatTask")
  public void executeXxlJob() throws InterruptedException {
    this.heartBeat();
  }

  private void heartBeat() {
    List<DeviceBase> deviceBases = deviceBaseService.list(new LambdaQueryWrapper<DeviceBase>()
            .eq(DeviceBase :: getDeviceType , "10"));
    for (DeviceBase deviceBase : deviceBases) {
      if (StringUtils.isBlank(deviceBase.getCabinetIp()) && StringUtils.isBlank(deviceBase.getCabinetPort())) {
        log.error("设备未设置ip和端口不进行操作!");
        continue;
      }
      // 旷视鸿图设备请求接口，请求成功不操作，请求失败，设备下线
      try {
        PersonUUIDSwitchResponse response = HT_DEVICE_POST.getJson(HongTuRequestUrl.GET_UUID_SWITCH,deviceBase.getCabinetIp(), deviceBase.getCabinetPort(), PersonUUIDSwitchResponse.class);
        if(ObjectUtil.equal(response.getCode(),0)){
          log.info("设备：{},心跳请求成功！" , deviceBase.getName());
          deviceBase.setDeviceState("1");
          deviceBase.setLastOnlineTime(new Date());
        }else{
          log.error("设备：{},心跳失败！请求结果" , deviceBase.getName() , JSON.toJSONString(response));
          deviceBase.setDeviceState("2");
        }
      } catch (Exception e) {
        deviceBase.setDeviceState("2");
        log.error("设备：{}下线！" , deviceBase.getName());
      }finally{
        deviceBaseService.updateById(deviceBase);
      }
    }
  }
}
